package com.mzmarket.market.module.service;

import com.mzmarket.market.module.entity.User;
import com.mzmarket.market.module.mapper.UserMapper;
import com.mzmarket.market.module.utils.SaltUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;

@Slf4j
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    public User getByPhone(String phone) {
        if (phone == null) {
            throw new RuntimeException("Phone cannot be null or empty");
        }
        return userMapper.getByPhone(phone);
    }

    public User extractByPhone(String phone) {
        if (phone == null) {
            throw new RuntimeException("Phone cannot be null or empty");
        }
        return userMapper.extractByPhone(phone);
    }

    public int insert(String phone,
                      String password,
                      String name,
                      String avatar) {
        int timeStamp = (int) (System.currentTimeMillis() / 1000);
        String salt = SaltUtil.generateSalt();//获取高随机度盐
        String newPassword = DigestUtils.md5DigestAsHex((password + salt).getBytes());//md5加密

        User user = new User()
                .setPhone(phone)
                .setPassword(newPassword)
                .setSalt(salt)
                .setName(name)
                .setAvatar(avatar)
                .setCreateTime(timeStamp)
                .setIsDeleted(0);
        return userMapper.insert(user);
    }

    public int update(String phone,
                      String password,
                      String salt,
                      String name,
                      String avatar) {

        if (getByPhone(phone) == null) {
            throw new RuntimeException("User not found");
        } else {
            User user = new User();
            user.setPhone(phone);
            user.setPassword(password);
            user.setSalt(salt);
            user.setName(name);
            user.setAvatar(avatar);
            return userMapper.update(user);
        }
    }

    public int delete(String phone) {
        if (phone == null) {
            throw new RuntimeException("Id cannot be null or empty");
        } else {
            if (getByPhone(phone) == null) {
                throw new RuntimeException("User not found");
            }
        }
        int timeStamp = (int) (System.currentTimeMillis() / 1000);
        return userMapper.delete(phone, timeStamp);
    }
}